package com.favccxx.search.domain.datamapper;

import com.favccxx.search.domain.datamapper.horizontal.HorizontalMapper;
import com.favccxx.search.domain.datamapper.vertical.VerticalMapper;
import com.favccxx.search.domain.datamapper.vertical.VerticalMapperUtil;
import com.favccxx.search.infrastructure.constant.MapperConstants;
import com.favccxx.search.infrastructure.exception.AppException;
import com.favccxx.search.infrastructure.exception.ExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author favccxx
 * @date 5/13/2020 11:39 PM
 */
@Slf4j
@Service
public class MapperService {

    @Autowired
    DataMapperRepo mapperRepo;

    public List<DataMapper> findAll() {
        return mapperRepo.findAll();
    }

    /**
     * Save or update data mapper
     *
     * @param dataMapper
     */
    public void saveDataMapper(DataMapper dataMapper) {
        mapperRepo.save(dataMapper);
    }


    /**
     * Get concept model mapper by concept model id
     *
     * @param conceptModelId
     * @return
     */
    public DataMapper findByConceptModelId(String conceptModelId) {
        return mapperRepo.findByConceptModelId(conceptModelId);
    }

    /**
     * Get concept model mapper by project id and concept model code
     *
     * @param projectId
     * @param conceptModelCode
     * @return
     */
    public DataMapper findByProjectIdAndConceptModelCode(String projectId, String conceptModelCode) {
        return mapperRepo.findByProjectIdAndConceptModelCode(projectId, conceptModelCode);
    }


    public String getMapperSqlByConceptModelId(String conceptModelId) {
        String sql = "";

        DataMapper mapper = findByConceptModelId(conceptModelId);
        if (mapper == null) {
            throw new AppException(ExceptionCode.Mapper.MAPPER_NOT_EXIST);
        }

        if (MapperConstants.HORIZONTAL_MAPPER_TYPE.equalsIgnoreCase(mapper.getMapperType())) {
            sql = buildHorizontalMapperSql(mapper);
            return sql;
        } else if (MapperConstants.VERTICAL_MAPPER_TYPE.equalsIgnoreCase(mapper.getMapperType())) {
            sql = VerticalMapperUtil.buildVerticalMapperSql(mapper);
            return sql;
        }

        return sql;
    }

    private String buildHorizontalMapperSql(DataMapper horizontalMapper) {
        String sql = "";
        return sql;
    }


}
